<script setup lang="ts">
import { defineProps, ref, watchEffect, withDefaults } from "vue";
import API from "@/api";
import message from "@arco-design/web-vue/es/message";
import {
  addQuestionUsingPost,
  listQuestionVoByPageUsingPost,
  updateQuestionUsingPost,
} from "@/api/questionController";
import { useRouter } from "vue-router";
import AiGenerateDrawer from "@/views/add/components/AiGenerateDrawer.vue";

//接收路由的参数
interface Props {
  appId: string;
}

const props = withDefaults(defineProps<Props>(), {
  appId: () => {
    return "";
  },
});
/**
 * 题目列表
 */
const questionContent = ref<API.QuestionContentDTO[]>([]);
const router = useRouter();
const oldQuestion = ref<API.QuestionVO>();

const loadDate = async () => {
  if (!props.appId) {
    return;
  }
  const res = await listQuestionVoByPageUsingPost({
    appId: props.appId as any,
    pageSize: 1,
    current: 1,
    sortField: "createTime",
    sortOrder: "descend",
  });
  if (res.data.code === 0 && res.data.data?.records) {
    oldQuestion.value = res.data.data.records[0]; //获取最新问题
    if (oldQuestion.value) {
      questionContent.value = oldQuestion.value.questionContent ?? []; //获取问题中的题目
    }
  } else {
    message.error("获取数据失败" + res.data.message);
  }
};

watchEffect(() => {
  loadDate();
});

const handleSubmit = async () => {
  //appId或者老题目什么都没有，直接返回即可
  if (!props.appId) {
    return;
  }
  //如果这个老题目存在说明是更新操作
  let res: any;
  if (oldQuestion.value) {
    res = await updateQuestionUsingPost({
      id: props.appId as any,
      questionContent: questionContent.value,
    });
  } else {
    res = await addQuestionUsingPost({
      appId: props.appId as any,
      questionContent: questionContent.value,
    });
  }
  if (res.data.code === 0) {
    message.success("操作成功 两秒钟之后会自动跳转");
    setTimeout(() => {
      router.push(`/app/detail/${props.appId}`);
      //可以在跳转的 URL 前加上 /，这样 router.push 就会解析为从根路径开始的绝对路径：
    }, 2000);
  } else {
    message.error("操作失败" + res.data.message);
  }
};

/**
 * 新增题目
 * @param index
 */
//splice 在 index 位置插入一个元素
const addQuestionContent = (index: number) => {
  questionContent.value.splice(index, 0, {
    title: "",
    options: [],
  });
};
/**
 * 删除题目
 * @param index
 */
//splice 在 index 位置删除一个元素
const deleteQuestionContent = (index: number) => {
  questionContent.value.splice(index, 1);
};

/**
 * 新增题目选项
 * @param index
 */
//splice 在 index 位置插入一个元素
const addQuestionContentOption = (
  question: API.QuestionContentDTO,
  index: number
) => {
  if (!question.options) {
    question.options = [];
  }
  question.options.splice(index, 0, {
    key: "",
    value: "",
  });
};
/**
 * 删除题目选项
 * @param index
 */
//splice 在 index 位置删除一个元素
const deleteQuestionContentOption = (
  question: API.QuestionContentDTO,
  index: number
) => {
  if (!question.options) {
    question.options = [];
  }
  question.options.splice(index, 1);
};

/**
 * 接收一键生成的AI抽屉组件传的参数
 * @param result
 */
const onAiGenerateSuccess = (result: API.QuestionContentDTO[]) => {
  questionContent.value = [...questionContent.value, ...result];
};

/**
 * 接收实时生成的AI抽屉组件传的参数
 * @param result
 */
const aiOnSSESuccess = (result: API.QuestionContentDTO) => {
  questionContent.value = [...questionContent.value, result];
};

/**
 * SSE开始连接
 * @param result
 */
const aiOnSSEStart = () => {
  message.success("开始连接");
};
/**
 * SSE连接关闭
 * @param result
 */
const aiOnSSEClose = () => {
  message.success("连接关闭");
};
</script>

<template>
  <div id="addQuestionPage">
    <h2 style="margin-bottom: 32px">设置题目</h2>
    <a-form
      :model="questionContent"
      :style="{ width: '480px' }"
      label-align="left"
      auto-label-width
      @submit="handleSubmit"
    >
      <a-form-item label="应用 id">
        {{ appId }}
      </a-form-item>
      <a-form-item label="题目列表" :content-flex="false" :merge-props="false">
        <a-space>
          <a-button @click="addQuestionContent(questionContent.length)">
            底部添加题目
          </a-button>
          <AiGenerateDrawer
            :appId="appId"
            :aiOnSuccess="onAiGenerateSuccess"
            :aiOnSSESuccess="aiOnSSESuccess"
            :aiOnSSEStart="aiOnSSEStart"
            :aiOnSSEClose="aiOnSSEClose"
          ></AiGenerateDrawer>
        </a-space>
        <!-- 遍历每道题目 -->
        <div v-for="(question, index) in questionContent" :key="index">
          <a-space size="large">
            <h3>题目 {{ index + 1 }}</h3>
            <a-button size="small" @click="addQuestionContent(index + 1)">
              添加题目
            </a-button>
            <a-button
              size="small"
              status="danger"
              @click="deleteQuestionContent(index)"
            >
              删除题目
            </a-button>
          </a-space>
          <a-form-item field="posts.post1" :label="`题目 ${index + 1} 标题`">
            <a-input v-model="question.title" placeholder="请输入标题" />
          </a-form-item>
          <!--  题目选项 -->
          <a-space size="large">
            <h4>题目 {{ index + 1 }} 选项列表</h4>
            <a-button
              size="small"
              @click="
                addQuestionContentOption(question, question.options.length)
              "
            >
              底部添加选项
            </a-button>
          </a-space>
          <a-form-item
            v-for="(option, optionIndex) in question.options"
            :key="optionIndex"
            :label="`选项 ${optionIndex + 1}`"
            :content-flex="false"
            :merge-props="false"
          >
            <a-form-item label="选项 key">
              <a-input v-model="option.key" placeholder="请输入选项 key" />
            </a-form-item>
            <a-form-item label="选项值">
              <a-input v-model="option.value" placeholder="请输入选项值" />
            </a-form-item>
            <a-form-item label="选项结果">
              <a-input v-model="option.result" placeholder="请输入选项结果" />
            </a-form-item>
            <a-form-item label="选项得分">
              <a-input-number
                v-model="option.score"
                placeholder="请输入选项得分"
              />
            </a-form-item>
            <a-space size="large">
              <a-button
                size="mini"
                @click="addQuestionContentOption(question, optionIndex + 1)"
              >
                添加选项
              </a-button>
              <a-button
                size="mini"
                status="danger"
                @click="
                  deleteQuestionContentOption(question, optionIndex as any)
                "
              >
                删除选项
              </a-button>
            </a-space>
          </a-form-item>
          <!-- 题目选项结尾 -->
        </div>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 120px">
          提交
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<style scoped></style>
